﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Common.PddApi;
using Common.Service;
using Common.Util;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using pinduoduo.Model;
using pinduoduo.Service;
using pinduoduo.Util;
using RestSharp;
using Sunny.UI;
using ThumbnailSharp;
using Tk.Soc.Share.Common.Helpers;
using static pinduoduo.Page.MainPage;
using static Sunny.UI.UIImageListBox;

namespace pinduoduo.Page
{
    public partial class OrderPage : UIPage
    {

        private PddTokenService pddTokenService;
        public OrderPage()
        {
            InitializeComponent();

            InitDataGridView();

            pddTokenService = new PddTokenService();
        }

        private void InitDataGridView()
        {
            OrderDataGridView.AddCheckBoxColumn("选择", "IsCheck").SetFixedMode(50);
            OrderDataGridView.AddColumn("序号", "num").SetFixedMode(50);
            OrderDataGridView.AddColumn("小号", "uid").SetFixedMode(150);
            OrderDataGridView.AddColumn("店铺", "mallName").SetFixedMode(200);
            OrderDataGridView.AddColumn("订单编号", "orderSn").SetFixedMode(230);
            OrderDataGridView.AddColumn("商品ID", "goodsId").SetFixedMode(130);
            OrderDataGridView.AddColumn("商品名", "goodsName").SetFixedMode(200);
            OrderDataGridView.AddColumn("SKU", "skuName").SetFixedMode(200);
            OrderDataGridView.AddColumn("订单状态", "orderState").SetFixedMode(100);
            OrderDataGridView.AddColumn("物流状态", "logisticsInfo").SetFixedMode(300);
            OrderDataGridView.AddColumn("快递单号", "logisticsOrderNo").SetFixedMode(100);
            OrderDataGridView.AddColumn("快递名称", "logisticsCompany").SetFixedMode(150);
            OrderDataGridView.AddColumn("订单类型", "order_type").SetFixedMode(100);

            OrderDataGridView.ReadOnly = true;
            OrderDataGridView.AutoGenerateColumns = false;

            UpdateData();
        }

        public async void UpdateData() 
        {
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            orderList = orderList.Reverse().ToList();
            DataGridViewPagination.DataSource = orderList;
            DataGridViewPagination.ActivePage = 1;
        }

        private async void uiButton4_Click(object sender, EventArgs e)
        {
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            if (!string.IsNullOrWhiteSpace(this.MaillTextBox.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.mallName) && x.mallName.Contains(this.MaillTextBox.Text));
            }

            if (!string.IsNullOrWhiteSpace(this.GoodIdTextBox.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.goodsId) && x.goodsId.Contains(this.GoodIdTextBox.Text));

            }

            if (!string.IsNullOrWhiteSpace(this.OrderStatusComboBox.Text.Trim()))
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains(this.OrderStatusComboBox.Text));

            }

            if (OrderTypeComboBox.Text != "全部订单")
            {
                orderList = orderList.Where(x => !string.IsNullOrWhiteSpace(x.order_type) && x.order_type.Contains(this.OrderTypeComboBox.Text));
            }

            this.OrderDataGridView.DataSource = null;
            orderList = orderList.Reverse().ToList();
            this.OrderDataGridView.DataSource = orderList;
        }

        private void DataGridViewPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            OrderDataGridView.DataSource = pagingSource;
        }

        private async void uiButton1_Click(object sender, EventArgs e)
        {
            var tokens = pddTokenService.GetAllToken();
            var orderList = GetSelectRows();
            foreach (Order order in orderList)
            {
                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                    continue;
                }
                //if (!string.IsNullOrWhiteSpace(order.orderState))
                //{
                //    if (order.orderState.Contains("待付款") || order.orderState.Contains("待收货") || order.orderState.Contains("待发货") || order.orderState.Contains("待分享") || order.orderState.Contains("待评价"))
                //    {

                //    }
                //    else
                //    {
                //        this.message.AppendText("订单不需要同步：" + order.uid + "\r\n");
                //    }
                //}
                try
                {
                    bool status = await PddApi.GetOrderStatus(order, token);
                    if (status)
                    {
                        await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
                    }
                    else
                    {
                        this.LogRichTextBox.AppendText("订单：" + order.orderSn + "获取订单信息失败  可能是小号过期了 \r\n");
                    }
                }
                catch
                {

                }


            }
            this.OrderDataGridView.Refresh();
        }

        private async void SyncAllOrderStatusButton_Click(object sender, EventArgs e)
        {
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var tokens = pddTokenService.GetAllToken();
            foreach (var order in orderList)
            {
                OrderStatus orderStatus = new OrderStatus();
                orderStatus.ts = PddApi.GetPddTime();

                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                    continue;
                }
                if (!string.IsNullOrWhiteSpace(order.orderState))
                {
                    if (order.orderState.Contains("待付款") || order.orderState.Contains("待收货") || order.orderState.Contains("待发货") || order.orderState.Contains("待分享") || order.orderState.Contains("待评价"))
                    {

                    }
                    else
                    {
                        continue;
                    }
                }


                bool status = await PddApi.GetOrderStatus(order, token);
                if (status)
                {
                    await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
                }
                else
                {
                    this.LogRichTextBox.AppendText("订单：" + order.orderSn + "获取订单信息失败  可能是小号过期了 \r\n");
                }
            }

            orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            //this.OrderDataGridView.Rows.Clear();
            this.OrderDataGridView.DataSource = new BindingList<Order>(orderList.ToList());
        }

        private async void uiButton3_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否确定收货（自动查找已经签收的订单）？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                //点确定的代码
            }
            else
            {        //点取消的代码    
                return;
            }
            var tokens = pddTokenService.GetAllToken();
            //var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();

            var orderList = GetSelectRows();

            foreach (var order in orderList)
            {
                if (!string.IsNullOrWhiteSpace(order.logisticsInfo) && order.logisticsInfo.Contains("已签收"))
                {
                    var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                    if (token == null)
                    {
                        this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                        continue;
                    }
                    await GoodsReceived(order, token);
                }

            }
        }

        private async void uiButton2_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("是否确定好评（自动查找待评价的订单）？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                //点确定的代码
            }
            else
            {        //点取消的代码    
                return;
            }
            var tokens = pddTokenService.GetAllToken(); //DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var list = orderList.Where(x => !string.IsNullOrWhiteSpace(x.logisticsInfo) && x.logisticsInfo.Contains("已签收")).ToList();

            foreach (DataGridViewRow item in this.OrderDataGridView.Rows)
            {
                var order = item.DataBoundItem as Order;
                if (!string.IsNullOrWhiteSpace(order.logisticsInfo) && order.logisticsInfo.Contains("已签收"))
                {
                    var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                    if (token == null)
                    {
                        this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                        continue;
                    }

                    if (!order.orderState.Contains("待评价"))
                    {
                        continue;
                    }
                    await GoodsReview(order, token);
                }

            }

        }

        private async void uiButton6_Click(object sender, EventArgs e)
        {

            DialogResult dr = MessageBox.Show("是否确定收货？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr != DialogResult.OK)
            {
                return;
            }

            var tokens = pddTokenService.GetAllToken();// DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();

            Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;

            List<string> imagePaths = new List<string>();
            if (this.uiImageListBox1.Items.Count > 0)
            {
                foreach (var item in this.uiImageListBox1.Items)
                {
                    ImageListItem listViewItem = item as ImageListItem;
                    imagePaths.Add(listViewItem.ImagePath);
                }
            }

            await GoodsReceivedAndGoodsReview(tokens, order, this.comment.Text, imagePaths);

        }
        /// <summary>
        /// 订单收货和好评
        /// </summary>
        /// <param name="tokens"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        private async Task GoodsReceivedAndGoodsReview(IEnumerable<PddToken> tokens, Order order, string comment, List<string> imagePaths)
        {
            if (order == null)
            {
                this.LogRichTextBox.AppendText("请选中一行进行操作\r\n");
                return;
            }

            var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            if (token == null)
            {
                this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                return;
            }

            string address = string.Empty;

            string errorMsg = string.Empty;
            address = G_Api.GetProxyIp(out errorMsg);
            if (string.IsNullOrWhiteSpace(address))
            {
                this.LogRichTextBox.AppendText("获取代理地址失败r\n");
                return;
            }
            this.LogRichTextBox.AppendText("使用代理IP：" + address + "\r\n");

            var result = await GoodsReceived(order, token, address);

            if (!result) { return; }

            Thread.Sleep(1000);


            var imagesUrlList = new List<Images>();


            foreach (var imagePath in imagePaths)
            {
                string base64 = null;

                try
                {
                    var resultBytes = new ThumbnailCreator().CreateThumbnailBytes(
                                            thumbnailSize: 900,
                                            imageStream: new FileStream(imagePath, FileMode.Open, FileAccess.Read),
                                            imageFormat: Format.Jpeg
                                        );
                    base64 = "data:image/jpg;base64," + Convert.ToBase64String(resultBytes);
                }
                catch (Exception)
                {
                    base64 = "data:image/jpg;base64," + ImageUtil.ImgToBase64String(imagePath);
                }
                var sign = await PddApi.Signature(token, null, "review_image");
                //var sign = await PddApi.UploadSignature(token);
                if (string.IsNullOrWhiteSpace(sign))
                {
                    this.LogRichTextBox.AppendText("上传图片获取签名失败请重试" + order.uid + "\r\n");
                    return;
                }
                var imageObj = await PddApi.UploadImage(token, sign, base64, null);
                if (imageObj == null)
                {
                    this.LogRichTextBox.AppendText("上传图片失败请重试" + order.uid + "\r\n");
                    return;
                }
                imagesUrlList.Add(imageObj);
                this.LogRichTextBox.AppendText("上传评论图片成功：" + imagePath + "\r\n");
            }

            await GoodsReview(order, token, comment, imagesUrlList, address);
        }

        private async Task GoodsReview(Order order, PddToken token, string comment = null, List<Images> imageUrlList = null, string daili = null)
        {
            Unrated unrated = new Unrated();
            unrated.goods_id = order.goodsId;
            unrated.order_sn = order.orderSn;
            unrated.anonymous = 0;
            unrated.timeline_sync_type = 1;
            unrated.comprehensive_dsr = 5;
            unrated.anti_content = "";
            if (comment != null)
            {
                unrated.comment = comment;
            }
            if (imageUrlList != null && imageUrlList.Count > 0)
            {
                unrated.pictures = imageUrlList;
            }

            string url = "http://mobile.yangkeduo.com/proxy/api/v2/order/goods/review?pdduid=" + order.uid;

            var restclient = new RestClient(url);

            if (!string.IsNullOrWhiteSpace(daili))
            {
                restclient.Proxy = RestClientUtil.CreateWebProxy(daili);
            }

            restclient.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1";

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("AccessToken", token.PDDAccessToken);
            request.AddHeader("Host", "mobile.yangkeduo.com");
            request.AddHeader("Origin", "http://mobile.yangkeduo.com");
            request.AddHeader("Referer", url);


            request.AddJsonBody(unrated);

            var response = await restclient.ExecuteAsync(request);
            if (!string.IsNullOrWhiteSpace(response.Content) && response.StatusCode == HttpStatusCode.OK)
            {
                order.orderState = "好评完成";
                await DataBaseHelper.SqLiteDBCon.UpdateAsync<Order>(order);
                this.LogRichTextBox.AppendText("订单：" + order.orderSn + "五星好评成功 \r\n");
            }
            else
            {
                LogHelper.Logger.Debug("好评失败：" + response.Content);
                this.LogRichTextBox.AppendText("订单：" + order.orderSn + "五星好评失败 \r\n");
            }
        }

        /// <summary>
        /// 订单收货
        /// </summary>
        /// <param name="order"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private async Task<bool> GoodsReceived(Order order, PddToken token, string daili = null)
        {
            string url = "http://apiv4.yangkeduo.com/order/" + order.orderSn + "/received?pdduid=" + order.uid;

            var restclient = new RestClient(url);


            restclient.UserAgent = "android Mozilla/5.0 (Linux; Android 5.1; OPPO R9tm Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.121 Mobile Safari/537.36";

            if (!string.IsNullOrWhiteSpace(daili))
            {
                restclient.Proxy = RestClientUtil.CreateWebProxy(daili);
            }

            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json, text/javascript, */*");
            request.AddHeader("Accept-Encoding", "gzip, deflate");
            request.AddHeader("AccessToken", token.PDDAccessToken);
            request.AddHeader("Host", "apiv4.yangkeduo.com");
            request.AddHeader("Referer", url);
            var response = await restclient.ExecuteAsync(request);
            if (!string.IsNullOrWhiteSpace(response.Content) && (response.Content.Contains("已确认收货，正在前往评价...") || response.Content.Contains("已确认收货成功，请勿重复点击")))
            {
                order.orderState = "待评价";
                await DataBaseHelper.SqLiteDBCon.UpdateAsync<Order>(order);
                this.LogRichTextBox.AppendText("订单：" + order.orderSn + "收获成功 \r\n");
                return true;
            }
            else
            {
                this.LogRichTextBox.AppendText("订单：" + order.orderSn + "收获失败 \r\n");
                this.LogRichTextBox.AppendText(response.Content + "\r\n");
                return false;
            }
        }

        private void uiButton5_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;//该值确定是否可以选择多个文件
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.jpg)|*.jpg";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //string file = dialog.FileName;
                //FileStream fs = File.Open(file, FileMode.Open);
                //ImageUtil.CutForCustom(fs, "D://test//1.jpg", 900, 1200,70);
                foreach (var item in dialog.FileNames)
                {
                    uiImageListBox1.AddImage(item, dialog.FileName);
                }

                //bindListView(file);
            }

        }

        private void uiButton7_Click(object sender, EventArgs e)
        {

            if (this.uiImageListBox1.Items.Count > 0)
            {
                foreach (var item in this.uiImageListBox1.Items)
                {
                    ImageListItem listViewItem = item as ImageListItem;

                }
                //uiImageListBox1.SelectedItem.ImagePath
                //uiImageListBox1.Items.
            }

            if (uiImageListBox1.SelectedItem != null)
            {
                int index = 0;
                foreach (var item in this.uiImageListBox1.Items)
                {
                    ImageListItem listViewItem = item as ImageListItem;

                    if (uiImageListBox1.SelectedItem.ImagePath == listViewItem.ImagePath)
                    {
                        break;
                    }
                    index++;
                }
                this.uiImageListBox1.Items.RemoveAt(index);
                //this.uiImageListBox1.Items.where();
            }
        }

        private void OrderDataGridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            //e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
            e.Row.Cells[1].Value = string.Format("{0}", (e.Row.Index + 1) + (this.DataGridViewPagination.ActivePage - 1) * DataGridViewPagination.PageSize);
        }

        private async void uiButton8_Click(object sender, EventArgs e)
        {
            //ShowWarningTip("正在努力开发中，请敬请期待，当前是演示模式");
            //return;
            //  DialogResult dr = MessageBox.Show("是否确定收货？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (!ShowAskDialog("是否批量评价？ 温馨提示：请按照指定的格式进行存放评论和图片"))
            {
                return;
            }

            var tokens = pddTokenService.GetAllToken();// DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
            var selectOrders = GetSelectRows();
           
            string path = AppDomain.CurrentDomain.BaseDirectory + "订单好评";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                //File.WriteAllText(path + "说明.txt", "好评内容");
                //Directory.CreateDirectory(path + "\\产品id\\1");
                //File.WriteAllText(path + "\\产品id\\1\\评论.txt", "好评内容");
                //Directory.CreateDirectory(path + "\\产品id\\1");
            }

            var ordesGroups = selectOrders.GroupBy(x => x.goodsId);
            foreach (var item in ordesGroups)
            {
                string goodId = item.Key;
                path = AppDomain.CurrentDomain.BaseDirectory + "订单好评\\" + goodId;
                if (!Directory.Exists(path))
                {
                    this.LogRichTextBox.AppendText("产品ID：" + goodId + " 评论文件夹不存在\r\n");
                    continue;
                }
                int index = 1;
                foreach (var order in item)
                {
                    string orderPath = path + "\\" + index;
                    if (!Directory.Exists(orderPath))
                    {
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个评论文件夹不存在\r\n");
                        break;
                    }

                    string contenx = orderPath + "\\评论.txt";
                    if (!File.Exists(contenx))
                    {
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个 评论不存在\r\n");
                        break;
                    }
                    DirectoryInfo folder = new DirectoryInfo(orderPath);
                    var images = folder.GetFiles("*.jpg");
                    List<string> imagesPaths = new List<string>();
                    if (images.Length < 1)
                    {
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个 好评图片不存在\r\n");
                      //  break;
                    }
                    else 
                    {
                        images.ForEach(x => { imagesPaths.Add(x.FullName); });
                    }
                   
                   
                    //this.LogRichTextBox.AppendText("开始任务：" + goodId + "好评内容" + File.ReadAllText(contenx) +" |||  总共："+ imagesPaths.Count+ " 个 好评图片\r\n");

                    await GoodsReceivedAndGoodsReview(tokens, order, File.ReadAllText(contenx), imagesPaths);
                    index++;
                }

            }

        }

        private void OrderPage_MouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    OrderDataGridView.ClearSelection();//清空选择项
                    OrderDataGridView.Rows[e.RowIndex].Selected = true;//获取被选中行索引
                    OrderDataGridView.CurrentCell = OrderDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    uiContextMenuStrip1.Show(MousePosition.X, MousePosition.Y);//弹出操作菜单
                }
            }
        }

        //private void uiContextMenuStrip1_Click(object sender, EventArgs e)
        //{
        //    var contextMenuStrip = sender as Sunny.UI.UIContextMenuStrip;

        //}

        private void OrderDataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    OrderDataGridView.ClearSelection();//清空选择项
                    OrderDataGridView.Rows[e.RowIndex].Selected = true;//获取被选中行索引
                    OrderDataGridView.CurrentCell = OrderDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    uiContextMenuStrip1.Show(MousePosition.X, MousePosition.Y);//弹出操作菜单
                }
            }
        }

        private async void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
           var item = sender as ToolStripMenuItem;
            Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;
            if (order == null) { return; }
            if (item.Text == "复制订单号")
            {

                Clipboard.SetDataObject(order.orderSn);
            }
            else if (item.Text == "付款")
            {
              await AutoPay(order);
            }
        }

        private async Task<PayResult> AutoPay(Order order)
        {

            if (order.orderState != "未支付")
            {
                Msg("目前支持 先下单后付款 模式的订单", true);
                return PayResult.Ignore;
            }

            var tokens = pddTokenService.GetAllToken();

            var pddToken = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
            if (pddToken == null)
            {
                Msg("小号没找到：" + order.uid + "",true);
                return PayResult.Ignore;
            }

            string errorMsg = string.Empty;

            string daili = G_Api.GetProxyIp(out errorMsg);

            if (string.IsNullOrEmpty(daili))
            {
                ShowErrorDialog("获取代理地址失败");
                return PayResult.No;
            }
            IRestResponse res;
            string url;
            if (order.order_type == "批发订单")
            {
                res = await PddPiFaApi.PiFPrepay(pddToken, order.parent_order_sn, daili);

                if (res.StatusCode != HttpStatusCode.OK)
                {
                    Msg("批发生成支付链接失败", true);
                    LogHelper.Logger.Debug("批发下单错误：" + res.Content);
                    return PayResult.Ignore;
                }

                Msg("生成支付链接成功");

                var jo = JObject.Parse(res.Content);
                var queryJo = jo["query"];
                var total_fee = jo["query"]["total_fee"].ToString();

                var gateway_url = jo["gateway_url"];

                StringBuilder stringBuilder = new StringBuilder();
                foreach (JToken grandChild in queryJo)
                {
                    var p = grandChild as JProperty;
                    string s = p.Name + ":" + p.Value;
                    stringBuilder.Append(p.Name);
                    stringBuilder.Append("=");
                    stringBuilder.Append(Uri.EscapeDataString(p.Value.ToString()));
                    stringBuilder.Append("&");
                }
                stringBuilder.Remove(stringBuilder.Length - 1, 1);
                url = gateway_url + "?" + stringBuilder.ToString();
                order.pay_url = url;
                order.goodsMoney = double.Parse(total_fee) * 100 + "";
            }
            else 
            {
                PDDOrderPrepay pDDOrderPrepay = new PDDOrderPrepay();
                pDDOrderPrepay.pay_app_id = 9;
                pDDOrderPrepay.version = 3;
                pDDOrderPrepay.order_sn = order.orderSn;
                pDDOrderPrepay.return_url = "http://mobile.yangkeduo.com/transac_wappay_callback.html?order_sn=" + order.orderSn + "&prepay_type=";
                pDDOrderPrepay.attribute_fields = new Model.Attribute_fields() { paid_times = 0, forbid_contractcode = "1", forbid_pappay = "1" };

                res = await PddApi.PddOrderPrepay(pddToken, pDDOrderPrepay, daili);

                if (res.StatusCode != HttpStatusCode.OK)
                {
                    Msg("下单失败,订单预付失败", true);
                    return PayResult.Ignore;
                }

                //订单预付
                PDDOrderPrepayResponse pDDOrderPrepayResponse = null;
                try
                {
                    pDDOrderPrepayResponse = JsonConvert.DeserializeObject<PDDOrderPrepayResponse>(res.Content);

                }
                catch (Exception e1)
                {
                    LogHelper.Logger.Error("下单失败,订单预付失败", e1);
                    Msg("下单失败,订单预付失败", true);
                    return PayResult.Ignore;
                }

                Msg("生成支付链接成功");

                string query = GetUriParam(pDDOrderPrepayResponse.query);
                url = pDDOrderPrepayResponse.gateway_url + "?" + query;
            }

            order.pay_url = url;
            order.orderState = "待支付";
            await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);

            BrowserFrom browserFrom = new BrowserFrom(true);
            browserFrom.AutoPay(url, Global.Global.PayPassword, true, 5000);
            var reslut = browserFrom.ShowDialog();
            if (!string.IsNullOrWhiteSpace(order.address_id))
            {
                await PddApi.DelAddressById(pddToken, order.address_id, daili);
            }

            if (reslut == DialogResult.OK)
            {
                return PayResult.OK;
            }
            return PayResult.Ignore;
        }


        /// <summary>
        /// Model对象转换为uri网址参数形式
        /// </summary>
        /// <param name="obj">Model对象</param>
        /// <param name="url">前部分网址</param>
        /// <returns></returns>
        public static string GetUriParam(object obj, string url = "")
        {
            PropertyInfo[] propertis = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            StringBuilder sb = new StringBuilder();
            sb.Append(url);
            //sb.Append("?");
            foreach (var p in propertis)
            {
                var v = p.GetValue(obj, null);
                if (v == null) v = "";

                sb.Append(p.Name);
                sb.Append("=");
                sb.Append(Uri.EscapeDataString(v.ToString()));//将字符串转换为它的转义表示形式，HttpUtility.UrlEncode是小写
                sb.Append("&");
            }
            sb.Remove(sb.Length - 1, 1);

            return sb.ToString();
        }

        private void Msg(string msg, bool error = false, bool enter = true)
        {
            if (error) this.LogRichTextBox.SelectionColor = Color.Red;

            LogRichTextBox.AppendText(msg);

            if (enter) LogRichTextBox.AppendText("\r\n");

            if (error) this.LogRichTextBox.SelectionColor = Color.Black;
        }
        private void OrderDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }

            DataGridViewCheckBoxCell dataGridViewCheckBoxCell = (DataGridViewCheckBoxCell)(this.OrderDataGridView.Rows[this.OrderDataGridView.CurrentCell.RowIndex].Cells[0]);
            if (Convert.ToBoolean(dataGridViewCheckBoxCell.EditedFormattedValue) == false)
            {
                dataGridViewCheckBoxCell.Value = true;
            }
            else
            {
                dataGridViewCheckBoxCell.Value = false;
            }
        }

        private async void uiButton9_Click(object sender, EventArgs e)
        {
            var orderList = GetSelectRows();
            if (orderList.Count() == 0) 
            {
                ShowWarningDialog("请先勾选要删除的数据");
                return;
            }
            if (ShowAskDialog("是否删除选中的" + orderList.Count() + "条数据？删除了不可恢复，请慎重使用"))
            {
                foreach (var item in orderList)
                {
                    DataBaseHelper.SqLiteDBCon.Delete(item);
                }
                ShowSuccessNotifier("删除完成");
                orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
                orderList = orderList.Reverse().ToList();
                DataGridViewPagination.DataSource = orderList;
                DataGridViewPagination.ActivePage = 1;
            }
        }

        private void OrderDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            
        }

        public IEnumerable<Order> GetSelectRows() 
        {
           var orderList = new List<Order>();
            foreach (DataGridViewRow dataGridViewRow in this.OrderDataGridView.Rows)
            {
              var order=  dataGridViewRow.DataBoundItem as Order;
                if (order.IsCheck) 
                {
                    orderList.Add(order);
                }
            }
            return orderList;
        }

        private void OrderDataGridView_SelectIndexChange(object sender, int index)
        {

        }

        private async void uiButton10_Click(object sender, EventArgs e)
        {

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "订单 (*.csv)|*.csv";
            dialog.DefaultExt = ".csv";
            dialog.Title = "保存订单";

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string filename = dialog.FileName;
                var orderList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<Order>();
                foreach (var item in orderList)
                {
                    

                    try
                    {
                        item.goodsMoney = Math.Round((decimal)(Convert.ToDouble(item.goodsMoney) / Convert.ToDouble(100)), 2).ToString() + " 元";
                    }
                    catch { }
                }
                var stringBuilder = CsvFileUtility.SaveDataToCSVFile<Order>(orderList.ToList());
                File.WriteAllText(filename, stringBuilder.ToString());
                ShowSuccessNotifier("保存成功");
            }
        }

        private void uiCheckBox5_ValueChanged(object sender, bool value)
        {
            foreach (DataGridViewRow dataGridViewRow in this.OrderDataGridView.Rows)
            {
                var order = dataGridViewRow.DataBoundItem as Order;
                order.IsCheck = uiCheckBox1.Checked;
            }
            this.OrderDataGridView.Refresh();
        }

        private void uiContextMenuStrip1_Click(object sender, EventArgs e)
        {
           
        }

        private async void PayToolStripMenuItem_Click(object sender, EventArgs e)
        { 
            Order order = this.OrderDataGridView.CurrentRow.DataBoundItem as Order;
            if (order == null) { return; }
            await AutoPay(order);
            Msg("任务完成，请手动同步订单最新状态");
        }

        private void uiButton11_Click(object sender, EventArgs e)
        {
            if (!ShowAskDialog("是否自动创建文件夹？ 温馨提示：此操作会将选中的订单进行自动创建文件夹，不会覆盖数据的"))
            {
                return;
            }

            var selectOrders = GetSelectRows();

            string path = AppDomain.CurrentDomain.BaseDirectory + "订单好评";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var ordesGroups = selectOrders.GroupBy(x => x.goodsId);
            foreach (var item in ordesGroups) 
            {
                string goodId = item.Key;
                path = AppDomain.CurrentDomain.BaseDirectory + "订单好评\\" + goodId;
                if (!Directory.Exists(path))
                {
                    this.LogRichTextBox.AppendText("产品ID：" + goodId + " 自动创建文件夹\r\n");
                    Directory.CreateDirectory(path);
                }
                int index = 1;
                foreach (var order in item) 
                {
                    string orderPath = path + "\\" + index;
                    if (!Directory.Exists(orderPath))
                    {
                        Directory.CreateDirectory(orderPath);
                        this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个，自动创建文件夹\r\n");
                    }
                    index++;
                    //string contenx = orderPath + "\\评论.txt";
                    //if (!File.Exists(contenx))
                    //{
                    //    this.LogRichTextBox.AppendText("产品ID：" + goodId + "第" + index + " 个 评论不存在\r\n");
                    //    break;
                    //}
                }
            }

        }

        private async void uiButton12_Click(object sender, EventArgs e)
        {
            var tokens = pddTokenService.GetShuaDanToken();
            //var tokens = DataBaseHelper.SqLiteDBCon.GetAll<PddToken>();
            string url = "http://mobile.yangkeduo.com/proxy/api/api/aristotle/order_list?";
            OrderModel orderModel = new OrderModel();

            foreach (var item in tokens)
            {

                var restclient = new RestClient(url);

                restclient.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64)";

                var request = new RestRequest(Method.POST);
                request.AddHeader("Content-Type", "application/x-www-form-urlencoded; Charset=UTF-8");
                request.AddHeader("Accept", "application/json, text/javascript, */*");
                request.AddHeader("Accept-Encoding", "gzip, deflate");
                request.AddHeader("AccessToken", item.PDDAccessToken);
                request.AddHeader("Host", "mobile.yangkeduo.com");
                request.AddHeader("Referer", url);
                request.AddCookie("PDDAccessToken", item.PDDAccessToken);

                orderModel.GetOrderType(this.sousuoComboBox.Text);
                request.AddObject(orderModel);
                var response = await restclient.ExecuteAsync(request);

                try
                {
                    if (!string.IsNullOrWhiteSpace(response.Content))
                    {
                        GoogOrder googOrder = JsonHelper.DeserializeObject<GoogOrder>(response.Content);
                        if (googOrder.orders == null || googOrder.orders.Count == 0)
                        {
                            continue;
                        }
                        foreach (var order in googOrder.orders)
                        {
                            if (order == null)
                            {
                                continue;
                            }
                            if (order.order_goods.Count == 0)
                            {
                                continue;
                            }
                            Order orderDao = new Order();
                            GoodOrderViewModel goodOrderViewModel = new GoodOrderViewModel();
                           
                            orderDao.uid = item.pdd_user_id;
                            //orderDao.token = item.PDDAccessToken;
                            orderDao.mallName = order.mall.mall_name;
                            orderDao.goodsId = order.order_goods[0].goods_id;
                            orderDao.goodsName = order.order_goods[0].goods_name;
                            orderDao.skuNumber = order.order_goods[0].sku_id;
                            orderDao.buyTime =TimeHelp.GetDateTimeFrom1970Ticks(order.order_time).ToString();
                            orderDao.orderSn = order.order_sn;
                            orderDao.goodsMoney = order.order_amount.ToString();
                            orderDao.orderState = order.order_status_prompt;

                            var result = await DataBaseHelper.SqLiteDBCon.GetAsync<Order>(orderDao.orderSn);
                            if (result != null)
                            {
                                Msg("更新本地订单信息：" + orderDao.orderSn + " \r\n");

                                await DataBaseHelper.SqLiteDBCon.UpdateAsync<Order>(orderDao);
                            }
                            else
                            {
                                Msg("新增订单到本地：" + orderDao.orderSn + " \r\n");

                                await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(orderDao);
                            }

                        }

                    }
                }
                catch
                {
                }
            }
        }

        private async void uiButton13_Click(object sender, EventArgs e)
        {

            if (!ShowAskDialog("是否将选中的订单进行退款？"))
            {
                return;
            }
          
            var tokens = pddTokenService.GetAllToken();

            var orderList = GetSelectRows();

            foreach (var order in orderList)
            {
                
                var token = tokens.Where(x => x.pdd_user_id == order.uid).FirstOrDefault();
                if (token == null)
                {
                    this.LogRichTextBox.AppendText("小号没找到：" + order.uid + "\r\n");
                    continue;
                }
                PddService.AfterSales(token, order);
                try
                {
                    bool status = await PddApi.GetOrderStatus(order, token);
                    if (status)
                    {
                        await DataBaseHelper.SqLiteDBCon.UpdateAsync(order);
                    }
                    else
                    {
                        this.LogRichTextBox.AppendText("订单：" + order.orderSn + "获取订单信息失败  可能是小号过期了 \r\n");
                    }
                }
                catch
                {

                }

            }
            this.OrderDataGridView.Refresh();
        }
    }
}
